package com.enfry.common.util.xml;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class XmlHelper {

	private static Logger logger = LoggerFactory.getLogger(XmlHelper.class);

	public static Map<String, Object> parseXml(InputStream inputStream) {
		// 从request中取得输入流
		try {
			// 读取输入流
			SAXReader reader = new SAXReader();
			Document document = reader.read(inputStream);

			// 得到xml根元素
			Element root = document.getRootElement();

			// 将解析结果存储在HashMap中
			Map<String, Object> map = parseXML(root);

			// 释放资源
			inputStream.close();
			inputStream = null;

			return map;
		} catch (IOException e) {
			logger.error("parseXml 响应失败 IOException", e);
			return new HashMap<String, Object>();
		} catch (DocumentException e) {
			logger.error("parseXml 响应失败 DocumentException", e);
			return new HashMap<String, Object>();
		}
	}

	public static Map<String, Object> parseXml(String str) {
		try {

			// 读取输入流
			SAXReader reader = new SAXReader();
			// 将字符串转换为
			Document document = reader.read(new ByteArrayInputStream(str
					.getBytes("GBK")));
			// 得到xml根元素
			Element root = document.getRootElement();

			// 将解析结果存储在HashMap中
			Map<String, Object> map = parseXML(root);

			return map;
		} catch (IOException e) {
			logger.error("parseXml 响应失败 IOException", e);
			return new HashMap<String, Object>();
		} catch (DocumentException e) {
			logger.error("parseXml 响应失败 DocumentException", e);
			return new HashMap<String, Object>();
		}
	}

	private static Map<String, Object> parseXML(Element parent) {
		// 将解析结果存储在HashMap中
		Map<String, Object> map = new HashMap<String, Object>();

		// 得到所有子节点
		List<Element> elementList = parent.elements();

		// 遍历所有子节点
		for (Element e : elementList) {
			if (e.isTextOnly()) {
				map.put(e.getName(), e.getText());
			} else {
				Map<String, Object> cMap = parseXML(e);
				map.put(e.getName(), cMap);
			}
		}
		return map;
	}
}
